package org.fengling.readingplatform.pay.strategy;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import jakarta.annotation.Resource;
import org.fengling.readingplatform.common.exception.FenglingException;
import org.fengling.readingplatform.model.entity.payment.PaymentInfo;
import org.fengling.readingplatform.model.vo.common.ResultCodeEnum;
import org.fengling.readingplatform.pay.factory.PaymentFactory;
import org.fengling.readingplatform.pay.service.PaymentInfoService;
import org.fengling.readingplatform.pay.template.AbstractPaymentHandler;
import org.fengling.readingplatform.pay.utils.AlipayProperties;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;

@Component
public class AlipayHandler extends AbstractPaymentHandler {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private PaymentInfoService paymentInfoService;

    @Resource
    private AlipayProperties alipayProperties ;

    // 支付宝下单
    @Override
    public String alipayMethod(String orderNo) throws AlipayApiException {
        //1. 保存支付记录
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);

        //2. 调用支付宝服务接口
        // 构建需要参数，进行调用
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 同步回调
        alipayRequest.setReturnUrl(alipayProperties.getReturnPaymentUrl());

        // 异步回调
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyPaymentUrl());

        // 准备请求参数，声明一个map集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no", paymentInfo.getOrderNo());
        map.put("product_code","QUICK_WAP_WAY");

        map.put("total_amount", new BigDecimal("0.01"));
        map.put("subject", paymentInfo.getContent());
        alipayRequest.setBizContent(JSON.toJSONString(map));

        // 发送请求
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayRequest);
        if(response.isSuccess()){
            return response.getBody();
        } else {
            throw new FenglingException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public String getPayment(String orderNo) throws AlipayApiException {
        return alipayMethod(orderNo);
    }

    @Override
    public String invokeCommon() {
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        PaymentFactory.register("Alipay", this);
    }

}
